package com.qd.panda.carpark;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.cdqidi.dto.ApiResult;
import com.cdqidi.dto.ApiResultWrapper;
import com.cdqidi.dto.DelDTO;
import com.cdqidi.util.page.PageUtil;
import com.cdqidi.valid.group.DefaultGroup;
import com.cdqidi.valid.group.UpdateGroup;
import com.qd.common.panda.domain.entity.carpark.CarParkDTO;
import com.qd.common.panda.domain.entity.rule.BillRuleSetDTO;
import com.qd.common.panda.domain.enums.GasStationCompanyNameEnum;
import com.qd.common.panda.domain.search.CarParkSearch;
import com.qd.common.sys.annotation.DataScope;
import com.qd.common.sys.annotation.OperatorInfo;
import com.qd.common.sys.enums.OperatorType;
import com.qd.hik.dto.parkinfo.HkParkReq;
import com.qd.panda.gas.sync.EGasSyncService;
import com.qd.panda.gas.sync.LastShellSyncService;
import com.qd.panda.service.dc.DcChargeStationService;
import com.qd.panda.service.park.CarParkAppointmentSetService;
import com.qd.panda.service.park.CarParkImgService;
import com.qd.panda.service.park.CarParkService;
import com.qd.panda.service.park.ParkHolderService;
import com.qd.panda.service.rule.BillRuleSetService;
import com.qd.panda.service.third.hk.HkParkSyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * WEB_停车场信息
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Validated
@RestController
@RequestMapping("/sys/carPark/")
@Slf4j
public class CarParkController {
    private final CarParkService carParkService;
    private final ParkHolderService parkHolderService;
    private final CarParkImgService carParkImgService;
    private final CarParkAppointmentSetService carParkAppointmentSetService;
    private final DcChargeStationService dcChargeStationService;
    private final BillRuleSetService billRuleSetService;
    private final LastShellSyncService lastShellSyncService;
    private final EGasSyncService eGasSyncService;
    private final HkParkSyncService hkParkSyncService;

    /**
     * 添加停车场信息
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @PostMapping(value = "/save")
    @PreAuthorize("@ps.hasPermission('parking:save')")
    @OperatorInfo(title = "添加停车场信息", operator = OperatorType.INSERT)
    public CarParkDTO save(@Validated({DefaultGroup.class}) @RequestBody CarParkDTO dto) {
        return parkHolderService.save(dto, true);
    }

    /**
     * 修改停车场信息
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @PutMapping(value = "/update")
    @PreAuthorize("@ps.hasPermission('parking:table:edit')")
    @OperatorInfo(title = "修改停车场信息", operator = OperatorType.UPDATE)
    public CarParkDTO update(@Validated({UpdateGroup.class, DefaultGroup.class}) @RequestBody CarParkDTO dto) {
        return parkHolderService.update(dto);
    }

    /**
     * 删除停车场信息
     *
     * @param delDTO 主键，多个用分号隔开
     * @return 页面对象
     */
    @DeleteMapping(value = "/delete")
    @PreAuthorize("@ps.hasPermission('parking:table:delete')")
    @OperatorInfo(title = "删除停车场信息", operator = OperatorType.DELETE)
    public ApiResultWrapper<Object> delete(@Validated @RequestBody DelDTO<String> delDTO) {
        final List<String> ids = delDTO.getIds();
        if (ids.size() == 1) {
            parkHolderService.removeById(ids.get(0));
        } else {
            parkHolderService.removeBatchIds(ids);
        }
        return ApiResult.success("删除成功");
    }

    /**
     * 获取停车场信息
     *
     * @param id 主键
     * @return 记录
     */
    @GetMapping(value = "/getById")
    public CarParkDTO getById(@Validated @NotBlank(message = DelDTO.ID_NULL_MSG) String id) {
        return carParkService.getByIdDto(id);
    }

    /**
     * 停车场信息列表
     *
     * @param dto 查询参数以及页数和每页显示条数
     * @return 列表信息
     */
    @GetMapping(value = "/page")
    @DataScope(orgAlias = "car")
    public IPage<CarParkDTO> page(CarParkSearch dto) {
        return carParkService.page(PageUtil.buildPage(dto), dto);
    }


    /**
     * 加载缓存
     *
     * @return 列表信息
     */
    @GetMapping(value = "/loadCache")
    @PreAuthorize("@ps.hasPermission('parking:table:cache')")
    @OperatorInfo(title = "加载停车场信息到缓存", operator = OperatorType.CLEAN)
    public ApiResultWrapper<Object> loadCache() {
        return parkHolderService.loadCache();
    }

    /**
     * 删除停车场图片介绍
     *
     * @param delDTO 主键，多个用分号隔开
     * @return 页面对象
     */
    @DeleteMapping(value = "/deleteCarImg")
    @PreAuthorize("@ps.hasPermission('parking:table:delete')")
    @OperatorInfo(title = "删除停车场图片介绍", operator = OperatorType.DELETE)
    public ApiResultWrapper<Object> deleteCarImg(@Validated @RequestBody DelDTO<String> delDTO) {
        final List<String> ids = delDTO.getIds();
        if (ids.size() == 1) {
            carParkImgService.removeById(ids.get(0));
        } else {
            carParkImgService.removeBatchIds(ids);
        }
        return ApiResult.success("删除成功");
    }

    /**
     * 删除停车场预约设置
     *
     * @param delDTO 主键，多个用分号隔开
     * @return 页面对象
     */
    @DeleteMapping(value = "/deleteAppointmentSet")
    @PreAuthorize("@ps.hasPermission('system:appointmentSet:delete')")
    @OperatorInfo(title = "添加停车场预约设置", operator = OperatorType.DELETE)
    public ApiResultWrapper<Object> deleteAppointmentSet(@Validated @RequestBody DelDTO<String> delDTO) {
        final List<String> ids = delDTO.getIds();
        if (ids.size() == 1) {
            carParkAppointmentSetService.removeById(ids.get(0));
        } else {
            carParkAppointmentSetService.removeBatchIds(ids);
        }
        return ApiResult.success("删除成功");
    }

    /**
     * 查询停车场费用设置码表
     *
     * @return 费用设置
     */
    @GetMapping(value = "/loadBillRuleSet")
    public List<BillRuleSetDTO> loadBillRuleSet() {
        return billRuleSetService.getListDto();
    }

    /**
     * 同步到系统组织
     *
     * @return 费用设置
     */
    @PostMapping(value = "/syncBathSysOrg")
    @PreAuthorize("@ps.hasPermission('parking:table:sync')")
    @OperatorInfo(title = "同步停车场信息到系统组织", operator = OperatorType.OTHER)
    public ApiResultWrapper<String> syncBathSysOrg() {
        parkHolderService.syncBathSysOrg();
        return ApiResult.success("同步成功");
    }

    /**
     * 生成葵花码
     *
     * @return 费用设置
     */
    @PostMapping(value = "/createQrCode")
    @PreAuthorize("@ps.hasPermission('charge:list:code')")
    @OperatorInfo(title = "停车场生成葵花码", operator = OperatorType.INSERT)
    public ApiResultWrapper<String> createQrCode(@RequestBody Map<String, String> map) {
        String parkId = map.get("parkId");
        if (!StringUtils.hasLength(parkId)) {
            return ApiResult.error("停车场ID不能为空");
        }
        return ApiResult.success(parkHolderService.createQrCode(parkId));
    }

    /**
     * 同步充电站信息
     */
    @GetMapping(value = "/syncDcChargeStation")
    @PreAuthorize("@ps.hasPermission('charge:list:sync')")
    @OperatorInfo(title = "从数据中台同步充电站信息", operator = OperatorType.INSERT)
    public ApiResultWrapper<String> syncDcChargeStation() {
        dcChargeStationService.sync(1, 10, LocalDateTime.now());
        return ApiResult.success("");
    }

    /**
     * 同步加油站站信息
     */
    @GetMapping(value = "/syncShellGasStation")
    @PreAuthorize("@ps.hasAnyPermissions('gas:list:sync,gas:list:syncE')")
    @OperatorInfo(title = "同步壳牌加油站站信息", operator = OperatorType.INSERT, isAuditLog = false)
    public ApiResultWrapper<String> syncShellGasStation(String type) {
        if (null == type) {
            log.info("同步所有加油站数据");
            lastShellSyncService.sync();
            eGasSyncService.sync();
        } else if (type.equals(GasStationCompanyNameEnum.EXTEND_SHELL.getCode())) {
            log.info("同步壳牌加油站数据");
            lastShellSyncService.sync();
        } else if (type.equals(GasStationCompanyNameEnum.EXTEND_SHELL_HIGH.getCode())) {
            return ApiResult.error("目前不区分壳牌高速");
        } else if (type.equals(GasStationCompanyNameEnum.E_JIA_YOU.getCode())) {
//            log.info("同步易加油数据");
            eGasSyncService.sync();
//            return ApiResult.error("目前不支持同步易加油数据");
        } else {
            return ApiResult.error("类型错误");
        }
        return ApiResult.success("");
    }

    /**
     * 获得全部停车场
     *
     * @param dto 查询参数以及页数和每页显示条数
     * @return 列表信息
     */
    @GetMapping(value = "/list")
    @DataScope(orgAlias = "car")
    public List<CarParkDTO> list(CarParkSearch dto) {
        return carParkService.getListDto(dto);
    }


    /**
     * 同步海康停车场数据
     */
    @GetMapping(value = "/syncHkPark")
    @PreAuthorize("@ps.hasAnyPermissions('parking:hk:sync')")
    @OperatorInfo(title = "同步海康停车场数据", operator = OperatorType.INSERT, isAuditLog = false)
    public ApiResultWrapper<String> syncHkPark() {
        HkParkReq req = new HkParkReq();
        req.setPageNo(1);
        req.setPageSize(99);
        hkParkSyncService.parks(req, LocalDateTime.now());
        req.freeData();
        return ApiResult.success("");
    }


}